/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.evolve.webbot.portal;

import  java.util.ArrayList;
import  java.util.List;
import  java.util.Iterator;
import  com.gargoylesoftware.htmlunit.WebClient;
import  com.gargoylesoftware.htmlunit.html.HtmlForm;
import  com.gargoylesoftware.htmlunit.html.HtmlPage;
import  com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import  com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import  com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import  com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import  com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import  org.apache.log4j.Logger;
import  java.io.IOException;
import  java.io.File;
import  java.io.FileOutputStream;
import  java.io.InputStream;
import  java.io.OutputStream;
import  javax.swing.JTextArea;

import com.evolve.webbot.beans.WebBotBeans;
import com.gargoylesoftware.htmlunit.html.*;
import com.evolve.webbot.util.Utileria;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import com.evolve.webbot.file.TxtLiverpoolDia;
import java.text.SimpleDateFormat;
import  com.evolve.webbot.file.CommonErrorFile;
import com.evolve.webbot.file.TxtFile;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.PrintWriter;
/**
 *
 * @author DarthAE
 */
public class LiverpoolVentaMes
{
   static Logger log = Logger.getLogger( LiverpoolVentaMes.class ); 
   
   private String path;
   private JTextArea jtextArea;
   public static String WB_MAIN_DIR        = "evolve-webbot";
   public static String LIVERPOOL_MAIN_DIR = "liverpool-webbot";
   public static String LIVERPOOL_PROP_DIR = "liverpool-properties";
   public static String LIVERPOOL_PROP_ARC = "LiverpoolPortal.properties";
   public static String LIVERPOOL_FILE_DIR = "liverpool-files";
   public static String LIVERPOOL_ARC_EXT  = ".html"; 

   public LiverpoolVentaMes(){}

   public LiverpoolVentaMes(String path)
   {
       this.path = path;
   }
   
   public LiverpoolVentaMes(String path,JTextArea jtextArea)
   {
       this.path = path;
       this.jtextArea=jtextArea;
   }

   public WebClient creaWebClient()
   {
       WebClient webClient = null;

       webClient = new WebClient();
       webClient.setJavaScriptEnabled(true);
       webClient.setThrowExceptionOnScriptError(false);
       webClient.setAjaxController(new NicelyResynchronizingAjaxController());

       return webClient;
   }  
   
   /*-------------------------------------------------------------------------*/
   public void getValuesPortalCompleto(WebClient webClient)
   {  

       log.info("Inicia descarga de información portal Liverpool Venta Mensual");
       
       int      j = 0;
       int      indPortalEjec  = 0;
       String   beanPropFilePath = null;
       Utileria util = new Utileria();
       String pathFichero=null;
       TxtLiverpoolDia txtLiverpool = new TxtLiverpoolDia();
       Date fileDate = new Date();
       SimpleDateFormat sdf01 = new SimpleDateFormat("ddMMyyyy");
       SimpleDateFormat sdf02 = new SimpleDateFormat("dd.MM.yyyy");
       
       CookieManager cookieMan = new CookieManager();
       cookieMan = webClient.getCookieManager();
       cookieMan.setCookiesEnabled(true);
       
       try{
            Properties properties = new Properties();            
                  
            beanPropFilePath = this.path+File.separator+WB_MAIN_DIR+
                                         File.separator+LIVERPOOL_MAIN_DIR+
                                         File.separator+LIVERPOOL_PROP_DIR+
                                         File.separator+"LiverpoolBean.properties";
            
            FileInputStream fis = new FileInputStream(beanPropFilePath);
            
            properties.load(fis);  
            indPortalEjec = Integer.parseInt(properties.getProperty("Portal.ejecuta"));           
            
         if(indPortalEjec==1)
         {    
            System.out.println("filepath "+beanPropFilePath);
            
            HtmlPage      p = (HtmlPage)webClient.getPage("https://proveedores.liverpool.com.mx/irj/portal");
            HtmlForm      f = (HtmlForm)p.getFormByName("logonForm");
            HtmlTextInput t = (HtmlTextInput)f.getInputByName("j_user");
            HtmlPasswordInput pass=(HtmlPasswordInput)f.getInputByName("j_password");
            
            t.setValueAttribute(properties.getProperty("Portal.user"));
            pass.setValueAttribute(properties.getProperty("Portal.passwd"));

            HtmlSubmitInput i =(HtmlSubmitInput)f.getInputByName("uidPasswordLogon");
            HtmlPage        r  = (HtmlPage)i.click();         
                
            HtmlPage pg3     = webClient.getPage("https://bwsext.liverpool.com.mx/sap/bw/BEx?sap-language=es&sap-client=400&accessibility=&style_sheet=http%3A%2F%2Fproveedores.liverpool.com.mx%3A80%2Firj%2Fportalapps%2Fcom.sap.portal.design.portaldesigndata%2Fthemes%2Fportal%2Flookfeel_portal%2FBIReports30%2FBIReports30_nn7.css%3F6.0.20.0.1&TEMPLATE_ID=BWR_VTAS_MENS_PROV_PES_SHIST");
            webClient.waitForBackgroundJavaScriptStartingBefore(3000);
            
            synchronized (pg3) {
                                 pg3.wait(3000);
                               }                   
               
            List headers = pg3.getWebResponse().getResponseHeaders();
            for( Iterator it = headers.iterator(); it.hasNext(); ) 
            {
              NameValuePair pair = (NameValuePair)it.next();
              log.info(pair.getName() + ' ' + pair.getValue());
            }
                   
            HtmlForm f1      = (HtmlForm)pg3.getFormByName("VARI");
            HtmlTextInput t1 = (HtmlTextInput)f1.getInputByName("VAR_VALUE_LOW_EXT_3");
                
            t1.setValueAttribute("424");
                
            HtmlTextInput t2 = (HtmlTextInput)f1.getInputByName("VAR_VALUE_LOW_EXT_12");
                
            t2.setValueAttribute("2804");
                   
            List<HtmlAnchor> anchorList1 =pg3.getAnchors();
            HtmlAnchor an3=null;
            HtmlAnchor an4=null;

            for (Iterator iter = anchorList1.iterator(); iter.hasNext();)
            {
               an3=(HtmlAnchor)iter.next();

                if(an3.getHrefAttribute().compareTo("Javascript:SAPBWBUTTON('PROCESS_VARIABLES','VAR_SUBMIT',' ')")==0)
                {
                   an4=an3;
                 }
            } 
                
            HtmlPage  pg4  = (HtmlPage)an4.click();
                    
            webClient.waitForBackgroundJavaScriptStartingBefore(3000);
            synchronized (pg4) {pg4.wait(3000);}
            
            List<HtmlAnchor> anchorList2 = pg4.getAnchors();
                
            int c = 0;
                
            for (Iterator iter = anchorList2.iterator(); iter.hasNext();)
            {
                     an3=(HtmlAnchor)iter.next();
                     
                     if(an3.getAttribute("href").compareTo("JavaScript:SAPBW(1,'','','EXPAND','0MATERIAL','Y')")==0)
                     {                     
                         an4=an3;
                     }              
                     c++;            
            }     
                
            HtmlPage pg5 = (HtmlPage)an4.click();
            
            log.info("La información descargada del portal Liverpool Venta Mensual es:\n");                           
            log.info(webClient.getPage("https://bwsext.liverpool.com.mx/sap/bw/BEx?SAP-LANGUAGE=ES&PAGENO=1&REQUEST_NO=2&CMD=EXPORT&DATA_PROVIDER=DATAPROVIDER_4&FORMAT=CSV&SEPARATOR=|").getWebResponse().getContentAsString());
            log.info("\n");
                   
            FileWriter  fichero = null;
            PrintWriter pw      = null;
            SimpleDateFormat sdf03 = new SimpleDateFormat("ddMMyyyy");
            
                       pathFichero="";
                       pathFichero=this.path+File.separator+WB_MAIN_DIR+
                                                          File.separator+LIVERPOOL_MAIN_DIR+
                                                          File.separator+LIVERPOOL_FILE_DIR+
                                                          File.separator+"LiverpoolVtaMes-data-"+
                                                          sdf03.format(new Date())+".txt";
                       
            TxtFile tf = new TxtFile();
            tf.writeFile(pathFichero,webClient.getPage("https://bwsext.liverpool.com.mx/sap/bw/BEx?SAP-LANGUAGE=ES&PAGENO=1&REQUEST_NO=2&CMD=EXPORT&DATA_PROVIDER=DATAPROVIDER_4&FORMAT=CSV&SEPARATOR=|").getWebResponse().getContentAsString());
            ArrayList<String> lines = tf.getLinesFromFile(pathFichero);
            tf.writeLiverpoolFile(pathFichero,lines);

            jtextArea.append("\n[-]archivo de datos Liverpool Venta Mensual generado: "+pathFichero);
            log.info("\n[-]archivo de datos generado: "+pathFichero);
                      
       }/*fin portal ejecuta*/  
       else
       if(indPortalEjec == 0)
       {
         log.info("[-]Portal Liverpool Venta Mensual Desactivado");
       }   
          
       }catch(Exception e){
                             log.error("[-]error de navegacion portal Liverpool Ventas Mensuales",e);
                          }
   }  
   
   public void terminaWebClient(WebClient webClient)
   {
       if(webClient!=null)
       {
           webClient.closeAllWindows();
       }
   }     
}
